package com.demo.minicat;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Map;

/**
 * 多线程来避免处理请求是阻塞 如果所有都在主线程中处理会阻塞
 *
 * @author: lipan
 * @date: 2021/10/2 9:59
 */

public class RequestProcessor extends Thread {


    private Socket socket;

    private Map<String, HttpServlet> servletMap;

    public RequestProcessor(Socket socket, Map<String, HttpServlet> servletMap) {
        this.socket = socket;
        this.servletMap = servletMap;
    }

    @Override
    public void run()  {
        Response response = null;
        InputStream inputStream = null;
        try {
            inputStream = socket.getInputStream();
            Request request = new Request(inputStream);
            response = new Response(socket.getOutputStream());
            //动态资源
            String uri = "/" + request.getUri();
            if (servletMap.containsKey(uri)) {
                HttpServlet httpServlet = servletMap.get(uri);
                httpServlet.service(request, response);
            } else {
                response.outputResource(request.getUri());
            }
        } catch (FileNotFoundException e) {
            response.outPut(HttpUtils.getHeader(HttpStatus.NOTFOUND));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                inputStream.close();
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
    }

